package J.算法.动态规划;

public class _剑指Offer47礼物的最大价值 {
    /**
     *
     * @param grid
     * @return
     */
    public int maxValue(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m+1][n+1];

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1])+grid[i-1][j-1];

            }

        }

        return dp[m][n];
    }

    /**
     * 优化思路：因为只是和前位数值有关系 所以可以原地修改
     * 第一行和 第一列就是累加
     * @param grid
     * @return
     */
    public int maxValue1(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m+1][n+1];

        //初始化第一行 第一列
        for (int j = 1; j < n; j++) {
            grid[0][j]+=grid[0][j-1];
        }
        for (int i = 1; i < m; i++) {
            grid[i][0] += grid[i-1][0];
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                grid[i][j] += Math.max(grid[i-1][j], grid[i][j-1]);

            }

        }

        return grid[m-1][n-1];
    }


}
